/*
 * @Description: 路由配置
 * @Author: DHL
 * @Date: 2021-12-07 08:52:06
 * @LastEditors: DHL
 * @LastEditTime: 2022-10-16 09:16:32
 */

import type { App } from 'vue'
import type { RouteRecordRaw } from 'vue-router'
import { createRouter, createWebHashHistory } from 'vue-router'

import { setupRouterGuard } from './guard'
import { basicRoutes } from './basicRoutes'
import { treeSerialize } from '/@/utils/twUtils'
import { AppRouteModule } from '../types/router'

const constantRoutes = [...basicRoutes]

/**
 * 创建路由
 */
export const router = createRouter({
  history: createWebHashHistory(import.meta.env.VITE_PUBLIC_PATH),
  routes: constantRoutes as unknown as RouteRecordRaw[],
  strict: true,
  scrollBehavior: () => ({ left: 0, top: 0 })
})

/**
 * 动态添加路由
 * @param routerList
 */
export function addRouter(routerList: AppRouteModule[]) {
  // 重置路由
  resetRouter()

  // 动态添加路由
  routerList.forEach((route) => {
    router.addRoute(route as unknown as RouteRecordRaw)
  })
}

/**
 * 重置路由
 */
export function resetRouter() {
  const whiteRoutesList = treeSerialize(constantRoutes, 'name')
  router.getRoutes().forEach((route) => {
    const { name } = route
    if (name && !whiteRoutesList.includes(name as string)) {
      router.hasRoute(name) && router.removeRoute(name)
    }
  })
}

/**
 * 配置路由
 * @param app
 */
export function setupRouter(app: App<Element>) {
  app.use(router)

  setupRouterGuard(router)
}
